﻿using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using JFnetcore.Models;
using Microsoft.AspNetCore.Http;
using Utility;
using static Utility.EnumUtil;
using Services.IService;
using Models;
using System.Linq.Expressions;
using Newtonsoft.Json;

namespace JFnetcore.Controllers
{
    public class LoginController : Controller
    {
        private IUsersService _userService;
        private IRolemenuService _rolemenuService;
        private ILogService _logService;
        public LoginController(IUsersService userService, IRolemenuService rolemenuService, ILogService logService)
        {
            _userService = userService;
            _rolemenuService = rolemenuService;
            _logService = logService;
        }

        /// <summary>
        /// 打开登录首页视图
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(string id)
        {
            if (id == "out")
            {
                HttpContext.Session.Remove("JinFanUser");
                return View();
            }
            else
            {

                string userJson = HttpContext.Session.GetString("JinFanUser");
                if (string.IsNullOrEmpty(userJson))
                {
                    return View();
                }
                else
                {
                    SessionModel userSession = JsonConvert.DeserializeObject<SessionModel>(userJson);
                    if (userSession != null)
                    {

                        return RedirectToAction("Index", "Home");
                    }
                    else
                        return View();
                }
            }

        }

        /// <summary>
        /// 表单提交，登陆接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Index(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                //检查用户信息
                var user = _userService.CheckUser(model.UserName, CommonUtil.Md5(model.Password));
                if (user != null)
                {
                    if (user.Disable == 1)
                    {

                        Expression<Func<RolemenuModel, bool>> where = LinqUtil.True<RolemenuModel>();
                        where = where.AndAlso(i => i.Role_Id == user.Role_id);
                        List<RolemenuModel> list = _rolemenuService.GetList(where);
                        SessionModel smodel = new SessionModel();
                        smodel.IP = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                        smodel.User = user;
                        smodel.RolemenuList = list;
                        //记录Session
                        HttpContext.Session.Set("JinFanUser", ByteConvertHelper.Object2Bytes(smodel));

                        _logService.Add(DateTime.Now, smodel.IP, user.Id.ToString(), (int)OperationEnum.Login, "");

                        //跳转到系统首页
                        return RedirectToAction("Index", "Home");

                    }
                    else
                    {
                        ViewBag.ErrorInfo = "无登录权限  " + user.Disabledesc;
                        return View();
                    }
                }
                ViewBag.ErrorInfo = "用户名或密码错误。";
                return View();
            }
            foreach (var item in ModelState.Values)
            {
                if (item.Errors.Count > 0)
                {
                    ViewBag.ErrorInfo = item.Errors[0].ErrorMessage;
                    break;
                }
            }
            return View(model);
        }

        /// <summary>
        /// 游客按钮登录接口
        /// </summary>
        /// <returns></returns>
        public IActionResult YKlogin()
        {
            var user = _userService.CheckUser("visitor", CommonUtil.Md5("jinfan"));
            List<RolemenuModel> list = _rolemenuService.GetListByRoleId(user.Role_id);
            SessionModel smodel = new SessionModel()
            {
                IP = Request.HttpContext.Connection.RemoteIpAddress.ToString(),
                User = user,
                RolemenuList = list
            };
            //记录Session
            HttpContext.Session.Set("JinFanUser", ByteConvertHelper.Object2Bytes(smodel));
            _logService.Add(DateTime.Now, smodel.IP, user.Id.ToString(), (int)OperationEnum.Login, "游客按钮直接登录");
            //跳转到系统首页
            return RedirectToAction("Index", "Home");
        }

        /// <summary>
        /// 邮件发送找回密码
        /// </summary>
        /// <param name="loginname"></param>
        /// <param name="email"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SendEmail(string loginname, string email)
        {
            if (!string.IsNullOrEmpty(loginname) && !string.IsNullOrEmpty(email))
            {
                UsersModel umodel = _userService.GetByLoginname(loginname);
                if (umodel != null)
                {
                    if (umodel.User_email != email)
                    {
                        return Content(ReturnJsonHelp.OutHandlerJson(false, "邮箱错误！"));
                    }
                    else
                    {
                        #region 生成密码
                        int number;
                        string strCode = string.Empty;
                        //随机数种子
                        Random random = new Random();

                        for (int i = 0; i < 6; i++) //校验码长度为4
                        {
                            //随机的整数
                            number = random.Next();

                            //字符从0-9,A-Z中随机产生,对应的ASCII码分别为
                            //48-57,65-90
                            number = number % 36;
                            if (number < 10)
                            {
                                number += 48;
                            }
                            else
                            {
                                number += 55;
                            }
                            strCode += ((char)number).ToString();
                        }
                        string newPwd = strCode;
                        #endregion
                        umodel.User_pwd = CommonUtil.Md5(newPwd);
                        if (_userService.Update(umodel))
                        {
                            MailUtil.Send(email, "金帆系统【找回密码】", "新密码：" + newPwd);
                            return Content(ReturnJsonHelp.OutHandlerJson(true, "邮件已经发送！"));
                        }
                        else
                        {
                            return Content(ReturnJsonHelp.OutHandlerJson(false, "初始密码失败！"));
                        }
                    }
                }
                else
                {
                    return Content(ReturnJsonHelp.OutHandlerJson(false, "账号不存在！"));
                }
            }
            else
            {
                return Content(ReturnJsonHelp.OutHandlerJson(false, "账号与邮件必填！"));
            }
        }

        /// <summary>
        /// 弹登录框
        /// </summary>
        /// <returns></returns>
        public IActionResult LoginForm()
        {
            return View();
        }

        /// <summary>
        /// 弹框登录接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult FormLogin(LoginModel model)
        {
            //检查用户信息
            var user = _userService.CheckUser(model.UserName, CommonUtil.Md5(model.Password));
            if (user != null)
            {
                if (user.Disable == 1)
                {

                    Expression<Func<RolemenuModel, bool>> where = LinqUtil.True<RolemenuModel>();
                    where = where.AndAlso(i => i.Role_Id == user.Role_id);
                    List<RolemenuModel> list = _rolemenuService.GetList(where);
                    SessionModel smodel = new SessionModel();
                    smodel.IP = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                    smodel.User = user;
                    smodel.RolemenuList = list;
                    //记录Session
                    HttpContext.Session.Set("JinFanUser", ByteConvertHelper.Object2Bytes(smodel));

                    _logService.Add(DateTime.Now, smodel.IP, user.Id.ToString(), (int)OperationEnum.Login, "");
                    return Content(ReturnJsonHelp.BJUIajaxJson(200, "登录成功！", "", "", "", true, "", ""));

                }
                else
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(300, "登录失败！没有登录权限。", "", "", "", false, "", ""));
                }
            }
            else
            {
                return Content(ReturnJsonHelp.BJUIajaxJson(300, "登录失败！账号密码错误。", "", "", "", false, "", ""));
            }
        }
    }
}
